package com.learn.smart.framework.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.learn.smart.framework.bean.Data;
import com.learn.smart.framework.bean.Handler;
import com.learn.smart.framework.bean.Param;
import com.learn.smart.framework.bean.View;
import com.learn.smart.framework.helper.BeanHelper;
import com.learn.smart.framework.helper.ConfigHelper;
import com.learn.smart.framework.helper.ControllerHelper;
import com.learn.smart.framework.helper.HelperLoader;
import com.learn.smart.framework.util.CodecUtil;
import com.learn.smart.framework.util.JsonUtil;
import com.learn.smart.framework.util.ReflectionUtil;
import com.learn.smart.framework.util.StreamUtil;

@WebServlet(urlPatterns="/*",loadOnStartup=0)
public class DispatcherServlet extends HttpServlet {

	private static final long serialVersionUID = -2113752222585570242L;

	/**
	 * Constructor of the object.
	 */
	public DispatcherServlet() {
		super();
	}
	
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init(ServletConfig servletConfig) throws ServletException {
		//初始化helper类
		HelperLoader.init();
		System.out.println("初始化完成");
		//获取servletContext
		ServletContext servletContext = servletConfig.getServletContext();
		ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
		jspServlet.addMapping(ConfigHelper.getAppJspPathStart()+"*");
		//注册处理静态资源的默认Servlet
//		ServletRegistration defultServlet = servletContext.getServletRegistration("defult");
//		defultServlet.addMapping(ConfigHelper.getAppAssetPath()+"*");
	}

	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		//获取请求路径
		String requestMethod = request.getMethod().toLowerCase();
		String requestPath = request.getPathInfo();
		Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
		if(handler!=null){
			//获取controller
			Class<?> controllerClass = handler.getControllerClass();
			Object controllerBean = BeanHelper.getBean(controllerClass);
			//获取参数
			Map<String,Object> paramMap = new HashMap<String,Object>();
			Enumeration<String> paramNames = request.getParameterNames();
			while(paramNames.hasMoreElements()){
				String paramName = paramNames.nextElement();
				String paramValue = request.getParameter(paramName);
				paramMap.put(paramName, paramValue);
			}
			String body = CodecUtil.decodeURL(StreamUtil.getString(request.getInputStream()));
			if(body!=null&&!"".equals(body)){
				String[] params = body.split("&");
				if(params!=null&&params.length>0){
					for(String param : params){
						String[] array = param.split("=");
						if(params!=null&&params.length==2){
							String paramName = array[0];
							String paramValue = array[1];
							paramMap.put(paramName, paramValue);
						}
					}
				}
			}
			Param param = new Param(paramMap);
			//调用action方法
			Method method = handler.getActionMethod();
			Object result = ReflectionUtil.invokeMentod(controllerBean, method, param);
			//处理返回值
			if(result instanceof View){
				View view = (View)result;
				String path = view.getPath();
				if(path!=null&&!"".equals(path)){
					if(path.startsWith("/")){
						response.sendRedirect(request.getContextPath()+path);
					}else{
						Map<String,Object> model = view.getModel();
						for(Map.Entry<String, Object> entry : model.entrySet()){
							request.setAttribute(entry.getKey(), entry.getValue());
						}
						request.getRequestDispatcher(ConfigHelper.getAppJspPathStart()+path+ConfigHelper.getAppJspPathEnd()).forward(request, response);
					}
				}
			}else if(result instanceof Data){
				Data data = (Data)result;
				Object model = data.getModel();
				if(model!=null){
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					PrintWriter write = response.getWriter();
					String json = JsonUtil.getJson(model);
					write.write(json);
					write.flush();
					write.close();
				}
			}
		}
	}



}
